# -*- coding:utf-8 -*-
# @Time : 2022/6/7 上午8:54 
# @Author : zdy
# @File : UIUserManage.py
# desc:
import os
import sys

from Class.Format import Serialization
from UI.UserManage import Ui_UserManage
from importQT import *
from Class.Devices import *
from UIClass.UIAddUser import UIAddUser
from Class.UserInfo import *

class UIUserManage(QDialog, Ui_UserManage):
    def __init__(self):
        super(UIUserManage, self).__init__()
        self.setupUi(self)
        self.setWindowFlags(Qt.WindowCloseButtonHint)
        self.setFixedSize(self.width(), self.height())
        self.applyResource()
        self.btnAdd.clicked.connect(self.btnAdd_clicked)
        self.btnDel.clicked.connect(self.btnDel_clicked)
        self.inittwData()

    def applyResource(self):
        self.setWindowIcon(getIcon())

    def inittwData(self):
        self.tableWidgetUsers.setColumnCount(2)
        # 设置表头粗体
        self.tableWidgetUsers.setHorizontalHeaderLabels(['用户名', '密码'])
        font = self.tableWidgetUsers.horizontalHeader().font()
        font.setBold(True)
        self.tableWidgetUsers.horizontalHeader().setFont(font)
        self.tableWidgetUsers.setSelectionBehavior(QAbstractItemView.SelectRows)  # 整行选中的方式
        self.tableWidgetUsers.horizontalHeader().setSectionsClickable(False)  # 表头不可点击
        self.tableWidgetUsers.horizontalHeader().setStretchLastSection(True)  # 最后一列填充
        self.tableWidgetUsers.setItemDelegateForColumn(0, EditDelegate(self))
        self.tableWidgetUsers.setItemDelegateForColumn(1, EditDelegate(self))
        for i in currentUsers.keys():
            self.addData(i)
        self.tableWidgetUsers.setShowGrid(True)  # 有数据时才起作用

    def addData(self, username:str):
        row = self.tableWidgetUsers.rowCount()
        self.tableWidgetUsers.insertRow(row)
        alignment = int(Qt.AlignHCenter | Qt.AlignVCenter)
        item = QTableWidgetItem()
        item.setData(Qt.DisplayRole, username)
        item.setTextAlignment(alignment)
        self.tableWidgetUsers.setItem(row, 0, item)
        item1 = QTableWidgetItem()
        item1.setData(Qt.DisplayRole, "***")
        item1.setTextAlignment(alignment)
        self.tableWidgetUsers.setItem(row, 1, item1)

    def btnAdd_clicked(self):
        w = UIAddUser()
        if w.exec() == 1:
            currentUsers.update({w.user.name:w.user})
            self.addData(w.user.name)
            currentUsers.pop(currentuser.name)
            currentUsers.update({currentuser.name: currentuser})

    def btnDel_clicked(self):
        ranges = self.tableWidgetUsers.selectedRanges()
        count = len(ranges)
        row = []
        for i in range(0, count):
            for j in range(ranges[i].topRow(), ranges[i].bottomRow() + 1):
                row.append(j)
        row.sort(key=int, reverse=True)  # 因为删除一行后，后面的行号都会变化，所以用sort方法将list进行降序排列
        if len(row)>0:
            if QMessageBox.Yes == QMessageBox.warning(self, "提示", "确定要删除用户吗？", QMessageBox.Yes, QMessageBox.No):
                for i in row:
                    if self.tableWidgetUsers.item(i,0).text() != adminuser.name:
                        currentUsers.pop(self.tableWidgetUsers.item(i,0).text())
                        self.tableWidgetUsers.removeRow(i)
                    else:
                        QMessageBox.warning(self, "提示", "不可删除admin账户", QMessageBox.Yes)

    def closeEvent(self, event) -> None:
        savecurrentUsers()

class EditDelegate(QItemDelegate):
    def __init__(self, parent):
        super(EditDelegate, self).__init__(parent)

    def createEditor(self, QWidget, QStyleOptionViewItem, QModelIndex):
        return None

